package com.acme.bankapp.domain.bank.transport;

import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.exception.BadStringToParseClient;
import com.acme.bankapp.domain.bank.exception.ConnectionException;
import com.acme.bankapp.service.bank.BankDataLoaderService;

import java.util.ArrayList;
import java.util.List;

public class ClientStub {

    private Connection connection;

    public ClientStub(Connection connection) {
        if (connection == null)
            throw new IllegalArgumentException("Connection is null");
        this.connection = connection;
    }

    public String addClient(Client client) throws ConnectionException {
        if (client == null)
            throw new IllegalArgumentException("Client is null");
        connection.writeLine("ADD");
        connection.writeLine(BankDataLoaderService.clientToString(client));
        return connection.readLine();
    }

    public List<Client> getClients() throws ConnectionException {
        List<Client> result = new ArrayList<>();

        connection.writeLine("STAT");
        int total = Integer.valueOf(connection.readLine());
        for (int i = 0; i < total; i++) {
            try {
                Client c = BankDataLoaderService.parseString(connection.readLine());
                result.add(c);
            } catch (BadStringToParseClient badStringToParseClient) {
                //TODO: log this
                badStringToParseClient.printStackTrace();
            }
        }
        return result;
    }
}
